﻿using System.Collections.Generic;
using System.Drawing;
using System.Runtime.Serialization;
using System.IO;

namespace MediaController.Server.Core.DataContracts
{
    [DataContract(Name = "DirectoryContract")]
    public class DirectoryContract
    {
        public string Path { get; set; }

        /// <summary>
        /// List of directories in folder
        /// </summary>
        [DataMember(Name = "Directories", IsRequired = true)]
        public DirectoryContract[] Directories { get; protected set; }

        /// <summary>
        /// List of files in folder
        /// </summary>
        [DataMember(Name = "Files", IsRequired = true)]
        public FileContract[] Files { get; protected set; }

        public Icon FolderIcon { get; protected set; }

        public DirectoryContract(string path)
            : this(path, true)
        {

        }

        protected DirectoryContract(string path, bool agregate)
        {
            Path = path;
            if (!agregate || !Directory.Exists(path)) return;

            var files = Directory.GetFiles(path);
            var directories = Directory.GetDirectories(path, "*.*", SearchOption.TopDirectoryOnly);
            FolderIcon = IconReader.GetFileIcon(path, IconReader.IconSize.Small, false);

            PopulateDirectories(directories);
            PopulateFiles(files);
        }

        private void PopulateDirectories(IEnumerable<string> directories)
        {
            var directoryContracts = new List<DirectoryContract>();
            foreach (var directory in directories)
            {
                directoryContracts.Add(new DirectoryContract(directory, false));
            }
            Directories = directoryContracts.ToArray();
        }

        private void PopulateFiles(IEnumerable<string> files)
        {
            var fileContracts = new List<FileContract>();
            foreach (var file in files)
            {
                fileContracts.Add(new FileContract(file));
            }
            Files = fileContracts.ToArray();
        }

        public override string ToString()
        {
            return Path;
        }
    }
}